package cn.gzsf.coolshark.controller;

import cn.gzsf.coolshark.mapper.UserMapper;
import cn.gzsf.coolshark.pojo.dto.UserLoginDTO;
import cn.gzsf.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpServletResponse response, HttpSession session){

        UserVO user = userMapper.selectByUserName(userLoginDTO.getUsername());
        if(user==null){
            return 3;
        }
        if(user.getPassword().equals(userLoginDTO.getPassword())){
            //判断是否需要记住用户名和密码
            if(userLoginDTO.getRem()){
                //创建两个Cookie，把用户名和密码放入Cookie对象
               Cookie c1 =  new Cookie("username",userLoginDTO.getUsername());
               Cookie c2 = new Cookie("password",userLoginDTO.getPassword());
               c1.setMaxAge(60*60*24*30);//设置保存时长
               c2.setMaxAge(60*60*24*30);
               //通过响应对象，将Cookie对象响应给客户端
               response.addCookie(c1);
               response.addCookie(c2);
            }
            //把登录成功的UserVO保存到Session里面
            session.setAttribute("user",user);
            return 1;
        }
        return 2;
    }

    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO)session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
